<?php
namespace Admin\Controller;
use Admin\Common\Page;
use Think\Model;
use Common\Model\BookModel;

class BookController extends BaseController {

    public function index() {
        $map['is_del'] = 0;
        $keywords = I('get.keywords');
        if (!empty($keywords)) {
            $map_or['book_id'] = $keywords;
            $map_or['tm'] = $keywords;
            $map_or['spbs'] = $keywords;
            $map_or['sm'] = ['like' , "%{$keywords}%"];
            $map_or['_logic'] = 'OR';
            $map['_complex'] = $map_or;
        }
        $is_null=I('get.is_null');
        if($is_null!=''){
            switch($is_null){
                case 'b_logo':
                case 'bdetail':
                case 'b_rec':$map[$is_null]="";break;
                case 'type':$map['_string']="book_id not in (select book_id from book_has_type)";break;
                default:break;
            }
        }
        $m = D('Book');
        $count = $m->where($map)->count();// 查询满足要求的总记录数
        $Page = new  Page($count , C('page.size'));// 实例化分页类 传入总记录数和每页显示的记录数(25)
        $show = $Page->show();// 分页显示输出
        $this->assign('page' , $show);// 赋值分页输出
        $data = $m->where($map)->relation(TRUE)->order('sort desc,book_id desc')->limit($Page->firstRow . ',' . $Page->listRows)->select();
        $this->data = $data;
        $this->display();
    }


    public function add() {
        //图书分类
        $book_type = M('book_type')->where(['pid' => 0])->select();
        foreach ($book_type as $k => $v) {
            $book_type[ $k ]['child'] = M('book_type')->where(['pid' => $v['type_id']])->select();
//            array_unshift($book_type[ $k ]['child'] , ['type_id' => 0 , 'name' => '请选择分类' ,]);
        }
        $this->book_type = $book_type;
        $this->display('edit');
    }

    public function edit() {
        $map['book_id'] = I('get.book_id');
        $data = M('book')->where($map)->find();
        $this->data = $data;
        //图书分类
        $book_has_type = M('book_has_type')->where(['book_id' => $map['book_id']])->select();
        foreach ($book_has_type as $k => $v) {
            $bookTypeArr[ $k ] = $v['type_id'];
        }
        $book_type = M('book_type')->where(['pid' => 0])->select();
        foreach ($book_type as $k => $v) {
            $book_type[ $k ]['child'] = M('book_type')->where(['pid' => $v['type_id']])->select();
            foreach ($book_type[ $k ]['child'] as $key => $value) {
                if (in_array($value['type_id'] , $bookTypeArr)) {
                    $book_type[ $k ]['child'][ $key ]['selected'] = 'selected';
                }
            }
        }
        $this->book_type = $book_type;
        $this->display();
    }

    public function doEdit() {
        $book_id = I('get.book_id');
        $data = I('post.');
        foreach ($data['type_id'] as $k => $v) {
            if (empty($v) && ($k==0 || $k==1)) {
                $this->error('图书类别前两项必须都选择');
            }
            if(!empty($v)){
                $book_has_type[ $k ]['type_id'] = $v;
                $book_has_type[ $k ]['book_id'] = $book_id;
            }
        }
        $data['bdetail'] = htmlspecialchars_decode($data['editorValue']);
        if ($_FILES['b_logo']['name'] != '') {
            $info = admin_upload();
            if ($info) {
                $data['b_logo'] = '/uploads/' . $info['b_logo']['savepath'] . $info['b_logo']['savename'];
            }
        }
        M('book')->startTrans();
        if (empty($book_id)) {
            //新增图书
            $r = M('book')->add($data);
            if (!empty($r)) {
                foreach ($book_has_type as $k => $v) {
                    $book_has_type[ $k ]['book_id'] = $r;
                }
                M('book_has_type')->addAll($book_has_type);
                M('book')->commit();
                $this->success('新增成功');
            } else {
                M('book')->rollback();
                $this->success('新增失败');
            }
        } else {
            //编辑图书
            M('book_has_type')->where(['book_id' => $book_id])->delete();
            $r_bookType = M('book_has_type')->addAll($book_has_type);
            $r = M('book')->where(['book_id' => $book_id])->save($data);
            if (!empty($r || $r_bookType)) {
                M('book')->commit();
                $this->success('修改成功',U('index'));
            } else {
                M('book')->rollback();
                $this->success('修改失败');
            }
        }
    }

    public function del() {
        $book_id = I('get.book_id');
        $r = M('book')->where(['book_id' => $book_id])->setField('is_del' , 1);
        if ($r !== FALSE) {
            $this->success('删除成功');
        } else {
            $this->error('删除失败，请联系管理员');
        }
    }

    //excel导入图书
    public function import() {
        $upload = new \Think\Upload();// 实例化上传类
        $upload->maxSize = 3145728;// 设置附件上传大小
        $upload->exts = ['xls' , 'xlsx'];// 设置附件上传类型
        $upload->rootPath = './uploads/excel/'; // 设置附件上传根目录
        $upload->savePath = ''; // 设置附件上传（子）目录
        $upload->autoSub = FALSE;
        // 上传文件 
        $info = $upload->upload();
        if (!$info) {// 上传错误提示错误信息
            $this->error($upload->getError());
        } else {// 上传成功
            $Book = M('book');
            $Book->startTrans();
            $data = excel_import($upload->rootPath . $info["excel"]["savename"] , $info["excel"]['ext']);
            //第一行为字段
            $colname = $data[0];
            unset($data[0]);
            foreach ($data as $k => $v) {
                $save = NULL;
                if (!empty($v[0]) && in_array('spbs' , $colname)) {
                    //获取数据
                    foreach ($colname as $key => $value) {
                        switch($value){
                            case 'cbrq':
                            case 'ysny':
                            case 'jlrq':$save[ $value ]=convert_etimetoptime($v[ $key ]);break;
                            default:$save[ $value ] = (string)$v[ $key ];break;
                        }
                    }
                    if($save['spbs']==''){
                        continue;
                    }
                    if(sizeof($save)==0){
                        break;
                    }
                    //查询是否存在此书
                    $count=$Book->where(['spbs'=>$save['spbs']])->count();
                    if($count>0){
                        //更新
                        $save['is_del'] = 0;
                        $map['spbs']=$save['spbs'];

                        unset($save['book_id']);
                        unset($save['spbs']);
                        unset($save['stock_rent']);
                        unset($save['stock_buy']);

                        $Book->where($map)->save($save);
                    }else{
                        //插入
                        unset($save['book_id']);
                        unset($save['stock_rent']);
                        unset($save['stock_buy']);
                        $book_id=$Book->add($save);
                        if(!$book_id){
                            $Book->rollback();
                            $this->error('导入错误,请检查');
                        }
                    }
                }
            }
            $Book->commit();
        }
        //        echo '操作成功';
        $this->success('操作成功');
    }

    //excel导入分类
    public function importType() {
        $upload = new \Think\Upload();// 实例化上传类
        $upload->maxSize = 3145728;// 设置附件上传大小
        $upload->exts = ['xls' , 'xlsx'];// 设置附件上传类型
        $upload->rootPath = './uploads/excel/'; // 设置附件上传根目录
        $upload->savePath = ''; // 设置附件上传（子）目录
        $upload->autoSub = FALSE;
        // 上传文件
        $file_name='excel_type'; //上传文件表单名
        $info = $upload->upload();
        if (!$info) {// 上传错误提示错误信息
            $this->error($upload->getError());
        } else {// 上传成功
            $Book = M('book');
            $Type=M('Book_has_type');
            $Book->startTrans();
            $data = excel_import($upload->rootPath . $info[$file_name]["savename"] , $info[$file_name]['ext']);

//            var_dump($data);
//            exit;
            /*array(4) {
                [0]=>array(2) {
                    [0]=> "spbs"
                    [1]=> "type"
                  }
                [1]=>array(2) {
                    [0]=> "3147104"
                    [1]=> "15,3"
                }
                [2]=>array(2) {
                    [0]=> "3183342"
                    [1]=> "15,2"
                }
                [3]=>array(2) {
                    [0]=> "3183343"
                    [1]=> "15,2"
                }
            }*/

            //第一行为字段
            $colname = $data[0];    //存放列名
            unset($data[0]);        //数据里去掉列名

//            echo "<pre>";
//            var_dump($colname);
//            var_dump($data);
//            exit;

            echo "<pre>";

            foreach ($data as $k => $v) {   //记录每一条记录（每一本书）
                $save = [];
                if (!empty($v[0]) && in_array('spbs' , $colname)) { //新华码不为空
                    //获取数据
                    foreach ($colname as $key => $value) {
                        switch($value){
                            case 'type':    //如果值为【分类】，为了得到存放分类所在列的键值
                                if((string)$v[ $key ]==''){
                                    $save[ 'type' ]=[];break;
                                }
                                $save[ 'type' ]=array_unique(explode(',',(string)$v[ $key ]));break;
                            default:        //如果值不是【分类】
                                $save[ $value ] = (string)$v[ $key ];break; //$save['spbs'] = 新华码
                        }
                    }

//                    var_dump($save);
                    /*array(2) {
                        ["spbs"]=> "3147104"
                        ["type"]=>
                            array(2) {
                                [0]=> "15"
                                [1]=> "3"
                            }
                    }*/

                    if($save['spbs']=='' || sizeof($save['type'])==0){  //如果新华码为空，或者没有分类
                        continue;   //退出
                    }
                    if(sizeof($save)==0){   //如果$save为空，退出
                        break;
                    }
                    //查询是否存在此书
                    $d=$Book->where(['spbs'=>$save['spbs']])->find();

//                    var_dump($d);exit;
                    /*array(24) {
                        ["book_id"]=>(4) "2128"
                        ["tm"]=>(13) "9787533674021"
                        ["isbn"]=>(13) "9787533674021"
                        ["spbs"]=>(7) "3147104"
                        ["sm"]=>(46) "埃米尔参加化装舞会/捣蛋鬼埃米尔"
                        ["zyz"]=>(56) "作者:(法)文森·库维里耶|译者:胡尉琳|绘画"
                        ["dj"]=>(5) "10.00"
                        ["bb"]=>(21) "安徽教育出版社"
                        ["cbrq"]=>(10) "2015-04-01"
                        ["ysny"]=>(10) "2015-04-01"
                        ["jlrq"]=>(10) "2015-03-30"
                        ["yxxl"]=>(5) "EAEB0"
                        ["yc"]=>(1) "1"
                        ["bc"]=>(1) "1"
                        ["kb"]=>(1) "4"
                        ["press_id"]=> NULL
                        ["stock_rent"]=>(2) "13"
                        ["sort"]=>(1) "0"
                        ["bdetail"]=>(639) "<p><span style="color: rgb(101, 101, 101); font-family: &#39;Hiragino Sans GB&#39;, Verdana, Simsun; font-size: 14px; line-height: 22px; text-indent: 32px; background-color: rgb(255, 255, 255);">狂欢节到了，埃米尔也得参加化装舞会，他却没有饰演比较流行的王子、蔬菜、海盗、牛仔、蜘蛛侠等各种角色，而是自作主张，出其不意地装扮成了“他”，是谁呢？埃米尔为什么这样做呢？妈妈和朋友们又是怎么看的呢？</span><img src="/ueditor/php/upload/image/20160820/1471661724688319.jpg"/><img src="/ueditor/php/upload/image/20160820/1471661730159460.jpg"/></p>"
                        ["b_rec"]=>(225) "本书讲述：狂欢节到了，埃米尔也要参加化装舞会，他却没有饰演比较流行的王子、蔬菜、海盗、牛仔、蜘蛛侠等各种角色，而是自作主张，出其不意地装扮成了“他”。"
                        ["b_logo"]=>(28) "/uploads/book/3147104-fm.jpg"
                        ["stock_buy"]=>(2) "13"
                        ["press"]=>(21) "安徽教育出版社"
                        ["is_del"]=>(1) "0"
                    }*/

                    if($d && $d['book_id']!=''){
                        //图书存在才处理分类
                        //先删除分类
                        $Type->where(['book_id'=>$d['book_id']])->delete(); //删除该图书下的所有分类信息
                        foreach($save['type'] as $kk=>$vv){
                            if($v!=''){
                                //更新分类
                                $r=$Type->data(['book_id'=>$d['book_id'],'type_id'=>$vv])->add();
                                if(!$r){
                                    $Book->rollback();
                                    $this->error('系统出错');
                                }
                            }
                        }
                        $content='批量导入图书分类，当前spbs:'.$save['spbs'].',导入分类id:'.json_encode($save['type']);
                        $log=[
                            'user_id'=>session('admin_user.user_id'),
                            'content'=>$content
                        ];
                        $log_id=M('admin_stocklog')->data($log)->add();
                        if(!$log_id){
                            $Book->rollback();
                            $this->error("日志记录失败失败");
                        }
                    }
                }
            }
            $Book->commit();
        }
//                echo '操作成功';
        $this->success('操作成功');
    }
    //图书详情，订单图书
    public function ob_search() {
        $tm = I("tm");
        $where='tm="'.$tm.'" or isbn="'.$tm.'"';
        $d = M("Book")->where($where)->select();
        if ($d) {
            $user_id=I('user_id');
            if($user_id!=''){
                foreach($d as $k=>$v){
                    $books = M("Book")->where(['sm' => $v['sm']])->getField('book_id', true);
                    array_push($books, $v['book_id']);
                    $map['book_id']= array('in', $books);
                    $map['user_id']=$user_id;
                    //是否借阅过
                    $d[$k]['is_rented']=M('view_order_has_book')->where($map)->count();
                }
            }
            $r = ["status" => "success" , "data" => $d];
        } else {
            $r = ["status" => "error" , "data" => "此码不存在"];
        }
        echo json_encode($r);
    }

    function export() {
        $map['is_del'] = 0;
        $Book = M('Book');
        $field=$this->get_export_field();
        $d = $Book->where($map)->field($field)->select();
        $file = excel_export($d);
        ouput_Browser($file);
    }

    function export_where(){
        $map['is_del'] = 0;
        $keywords = I('get.keywords');
        if (!empty($keywords)) {
            $map_or['book_id'] = $keywords;
            $map_or['tm'] = $keywords;
            $map_or['spbs'] = $keywords;
            $map_or['sm'] = ['like' , "%{$keywords}%"];
            $map_or['_logic'] = 'OR';
            $map['_complex'] = $map_or;
        }
        $is_null=I('get.is_null');
        if($is_null!=''){
            switch($is_null){
                case 'b_logo':
                case 'bdetail':
                case 'b_rec':$map[$is_null]="";break;
                default:break;
            }
        }
        $Book = M('Book');
        $field=$this->get_export_field();
        $d = $Book->where($map)->field($field)->select();
        $file = excel_export($d);
        ouput_Browser($file);
    }

    function get_export_field(){
        return 'book_id,tm,spbs,sm,zyz,dj,bb,cbrq,ysny,jlrq,yxxl,yc,bc,kb,stock_rent,sort,stock_buy,press';
    }
}